package com.eascs.web.o2o.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.dao.PageResult;
import com.eascs.app.exception.ControllerException;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.form.LoanBalanceForm;
import com.eascs.web.o2o.web.service.BuildExcelService;
import com.eascs.web.o2o.web.service.LoanBalanceService;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;

/**
 * 业务按余额统计
 */
@Controller
@RequestMapping("/balance")
public class LoanBalanceController extends BaseMasterViewController {
	@Override
	public void preHandle() {
		super.preHandle();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "loanBalance");
	}
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	LoanBalanceService loanBalanceService;


	/**
	 * 
	 * @Title: page
	 * @Description: TODO 按照平台维度
	 * @author user
	 * @param form
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年4月26日 下午4:08:36
	 */
	
	@RequestMapping("/platPage")
	public String platPage(LoanBalanceForm form) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "loanBalance");
		String o2ourl = "/restBalance/platRestPage";
		if(form!=null){
			String ltd = form.getLtd()==null?"":form.getLtd();
			String selectDate = form.getSelectDate();
			o2ourl = UrlUtil.appendUrl(o2ourl, "ltd",ltd);
			o2ourl = UrlUtil.appendUrl(o2ourl, "selectDate",selectDate);
			o2ourl=o2ourl+"&showPage=";
		}else{
			o2ourl= o2ourl+"?showPage=";
		}
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", form);
		return "balance/loanBalancePlatList";
	}

	
	/**
	 * 
	 * @Title: page
	 * @Description: TODO 按照地级市维度
	 * @author user
	 * @param form
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年4月26日 下午4:08:36
	 */
	
	@RequestMapping("/cityPage")
	public String cityPage(LoanBalanceForm form) {
		
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "CityBalance");
		String o2ourl = "/restBalance/cityRestPage";
		if(form!=null){
			String city = form.getCity();
			String province = form.getProvince();
			String selectDate = form.getSelectDate();
			o2ourl = UrlUtil.appendUrl(o2ourl, "city",city);
			o2ourl = UrlUtil.appendUrl(o2ourl, "province",province);
			o2ourl = UrlUtil.appendUrl(o2ourl, "selectDate",selectDate);
			o2ourl=o2ourl+"&showPage=";
		}else{
			o2ourl= o2ourl+"?showPage=";
		}
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", form);
		return "balance/loanBalanceCityList";
	}
	
	
	
	
	/**
	 * 
	 * @Title: page
	 * @Description: TODO 按照省区维度
	 * @author user
	 * @param form
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年4月26日 下午4:08:36
	 */
	
	@RequestMapping("/provincePage")
	public String provincePage(LoanBalanceForm form) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "ProvinceBalance");
		String o2ourl = "/restBalance/provinceRestPage";
		if(form!=null){
			String province = form.getProvince();
			String selectDate = form.getSelectDate();
			o2ourl = UrlUtil.appendUrl(o2ourl, "province",province);
			o2ourl = UrlUtil.appendUrl(o2ourl, "selectDate",selectDate);
			o2ourl=o2ourl+"&showPage=";
		}else{
			o2ourl= o2ourl+"?showPage=";
		}
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", form);
		return "balance/loanBalanceProvinceList";
	}
	
	
	

	
	
	@RequestMapping("/downloadPlatBalanceForm")
	public void downloadPlatform(LoanBalanceForm form, HttpServletResponse httpServletResponse,
				HttpServletRequest request) {
			form.setPageSize(Integer.MAX_VALUE);
			PageResult<Object[]> pageResult = loanBalanceService.LoanBalancePlatProgress(form);
			saveReportStatByPlatform(pageResult.getData());
			String path = MonReportController.class.getResource("/excelTemplate").getPath();
			StringBuffer s = new StringBuffer();
			String outPath = s.append(path).append("/platBalance.xls").toString();//生成文件
			OutputStream os = null;
			try {
				String outfile = "贷款余额-平台维度.xls";
				String userAgent = request.getHeader("User-Agent");
				byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
				outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
				File f = new File(outPath);
				if (!f.exists())
					throw new RuntimeIOException("file not found");
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				IoUtil.fileToOutputStream(f, byteArrayOutputStream);
				os.write(byteArrayOutputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
	}
		
	@RequestMapping("/downloadCityBalanceForm")
	public void downloadCityform(LoanBalanceForm form, HttpServletResponse httpServletResponse,
				HttpServletRequest request) {
			form.setPageSize(Integer.MAX_VALUE);
			PageResult<Object[]> pageResult = loanBalanceService.LoanBalanceCityProgress(form);
			saveReportStatByCityform(pageResult.getData());
			String path = MonReportController.class.getResource("/excelTemplate").getPath();
			StringBuffer s = new StringBuffer();
			String outPath = s.append(path).append("/cityBalance.xls").toString();//生成文件
			OutputStream os = null;
			try {
				String outfile = "贷款余额-地级市维度.xls";
				String userAgent = request.getHeader("User-Agent");
				byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
				outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
				File f = new File(outPath);
				if (!f.exists())
					throw new RuntimeIOException("file not found");
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				IoUtil.fileToOutputStream(f, byteArrayOutputStream);
				os.write(byteArrayOutputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
	}
	
	@RequestMapping("/downloadProvinceBalanceForm")
	public void downloadProvinceform(LoanBalanceForm form, HttpServletResponse httpServletResponse,
				HttpServletRequest request) {
		form.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = loanBalanceService.LoanBalanceProvinceProgress(form);
		saveReportStatByProvinceform(pageResult.getData());
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/provinceBalance.xls").toString();//生成文件
		OutputStream os = null;
		try {
			String outfile = "贷款余额-省区维度.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
		
		
	public String saveReportStatByPlatform(List<Object[]> data) {
			// 模板
			String soucreFileName = "/excelTemplate/plat_balance.xls";//模版文件
			// 输出路径
			String path = MonReportController.class.getResource("/excelTemplate").getPath();
			StringBuffer s = new StringBuffer();
			String outPath = s.append(path).append("/platBalance.xls").toString();//生成文件

			// 包含的列
			int col = 8;
			// 需要统计的列
			int[] arr = {  };
			// 开始的表格，行，列
			int sheetIndex = 0;
			int rowIndex = 2;
			int columnIndex = 0;
			BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList("贷款余额-平台维度"),
					sheetIndex, rowIndex, columnIndex);

			// 生产excel
			write(soucreFileName, outPath, bankRowWriteHandler);

			return path + "/" + outPath;
	}
		
	public String saveReportStatByCityform(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate/city_balance.xls";//模版文件
		// 输出路径
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/cityBalance.xls").toString();//生成文件

		// 包含的列
		int col = 7;
		// 需要统计的列
		int[] arr = {  };
		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 2;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList("贷款余额-地级市维度"),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		return path + "/" + outPath;
	}
	
	public String saveReportStatByProvinceform(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate/province_balance.xls";//模版文件
		// 输出路径
		String path = MonReportController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/provinceBalance.xls").toString();//生成文件

		// 包含的列
		int col = 6;
		// 需要统计的列
		int[] arr = {  };
		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 2;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList("贷款余额-省区维度"),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		return path + "/" + outPath;
	}
		
		
	public void write(String soucreFileName, String outPath, BankRowWriteHandler bankRowWriteHandler) {
			IoUtil.createDirectorieIfMissing(new File(outPath).getParentFile());
			try {
				ExcelApiHelper.writeHandle(new FileOutputStream(outPath),
						BuildExcelService.class.getResourceAsStream(soucreFileName), bankRowWriteHandler);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				throw new ControllerException(e);
			}
	}
		
		
}
